<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover" class="search-card">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="货件编码" prop="shipmentConfirmationId">
              <el-input v-model="queryParams.shipmentConfirmationId" placeholder="请输入货件编码" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="归属工厂" prop="factory">
              <!-- <el-input v-model="queryParams.factory" placeholder="请输入归属工厂" clearable @keyup.enter="handleQuery" /> -->
              <el-select v-model="queryParams.factory" placeholder="请选择下发工厂">
                <el-option v-for="factory in factoryOptions" :key="factory.id" :label="factory.name"
                  :value="factory.name"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="店铺名称" prop="shopName">
              <el-input v-model="queryParams.shopName" placeholder="请输入归属店铺名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="追踪编号" prop="trackingNumber">
              <el-input v-model="queryParams.trackingNumber" placeholder="请输入货件追踪编号" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="员工姓名" prop="employeeName">
              <!-- <el-input v-model="queryParams.employeeName" placeholder="请输入员工姓名" clearable @keyup.enter="handleQuery" /> -->
              <el-select v-model="queryParams.employeeId" placeholder="请选择员工">
                <el-option v-for="employee in employeeOptions" :key="employee.id" :label="employee.name"
                  :value="employee.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="头程方式" prop="firstJourney">
              <el-input v-model="queryParams.firstJourney" placeholder="请输入头程方式" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="产品标条码" prop="fnsku"> 
              <el-input v-model="queryParams.fnsku" placeholder="请输入产品标条码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="产品名称英文" prop="msku">
              <el-input v-model="queryParams.msku" placeholder="请输入产品名称英文" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option label="待确认" value="0" />
                <el-option label="待处理" value="1" />
                <el-option label="审核中" value="2" />
                <el-option label="已驳回" value="3" />
                <el-option label="审核通过" value="4" />
              </el-select>
            </el-form-item>
            <el-form-item label="下单时间" prop="orderTime">
              <el-date-picker v-model="dateRangeOrderTime" type="daterange" value-format="YYYY-MM-DD HH:mm:ss"
                range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" clearable
                @change="handleDateRangeChange" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery" class="btn-animate">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery" class="btn-animate">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" class="table-card">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="upload" @click="handleImport" v-hasPermi="['ymxbh:shipment:add']"
              class="btn-animate">订单导入</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['ymxbh:shipment:edit']" class="btn-animate">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['ymxbh:shipment:remove']" class="btn-animate">删除</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['ymxbh:shipment:export']"
              class="btn-animate">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handSyncOrderList" 
              class="btn-animate">订单同步</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleMerge" 
              class="btn-animate">订单合并</el-button>
          </el-col>
          
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="shipmentList" @selection-change="handleSelectionChange"
        class="shipment-table small-font" header-cell-class-name="shipment-table-header" row-class-name="shipment-table-row"
        highlight-current-row>
        <el-table-column type="selection" width="40" align="center" />
        <el-table-column type="expand" width="40">
          <template #default="props">
            <div class="product-table-container">
              <el-table :data="props.row.productList" border style="width: 100%" class="product-table"
                header-cell-class-name="product-table-header">
                <el-table-column label="产品图片" align="center" width="100">
                  <template #default="scope">
                    <el-image v-if="scope.row.image" :src="scope.row.image" :preview-src-list="[scope.row.image]"
                      preview-teleported fit="cover" style="width: 50px; height: 50px" class="product-image" />
                    <span v-else class="no-image">无图片</span>
                  </template>
                  <!-- <image-preview :images="[props.row.image]" /> -->
                </el-table-column>
                <el-table-column label="产品名称" align="center" prop="productName" width="100" />
                <el-table-column label="FNSKU" align="center" prop="fnsku" width="100" />
                <el-table-column label="MSKU" align="center" prop="msku" width="100" />
                <el-table-column label="数量" align="center" prop="quantity" width="70" />
                <el-table-column label="箱内数量" align="center" prop="quantityinbox" width="70" />
                <el-table-column label="箱数" align="center" prop="boxNumber" width="70" />
                <el-table-column label="对应箱号" align="center" prop="boxId" width="100" />
                <el-table-column label="重量" align="center" prop="weight" width="70" />
                <el-table-column label="追踪编号" align="center" prop="trackingNumber" width="100" />
                <el-table-column label="备注" align="center" prop="remark" width="100" />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
                  <template #default="scope">
                    <el-tooltip content="修改" placement="top">
                      <el-button link type="primary" icon="Edit" @click="handleUpdateProduct(scope.row)"
                        v-hasPermi="['ymxbh:product:edit']" class="action-btn"></el-button>
                    </el-tooltip>
                    <!-- <el-tooltip content="删除" placement="top">
                      <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['ymxbh:shipment:remove']" class="action-btn"></el-button>
                    </el-tooltip> -->
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="货件id" align="center" prop="id" width="80" /> -->
        <el-table-column label="货件编码" align="center" prop="shipmentConfirmationId" width="100" />
        <el-table-column label="FBA地址" align="center" prop="warehouseId" width="50" />
        <el-table-column label="归属工厂" align="center" prop="factory" width="80" />
        <el-table-column label="店铺名称" align="center" prop="shopName" width="100" />
        <el-table-column label="发货材料及编号" align="center" prop="materialAndNumber" width="150" />
        <el-table-column label="追踪编号" align="center" prop="trackingNumber" width="100" />
        <el-table-column label="员工姓名" align="center" prop="employeeName" width="80" />
        <el-table-column label="头程方式" align="center" prop="firstJourney" width="100" />
        <el-table-column label="送货地址" align="center" prop="shippingAddress" width="150" />
        <el-table-column label="下单时间" align="center" prop="orderTime" width="100">
          <template #default="scope">
            <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发货时间" align="center" prop="shipmentsTime" width="100">
          <template #default="scope">
            <span>{{ parseTime(scope.row.shipmentsTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="80">
          <template #default="scope">
            <dict-tag :options="statusOptions" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
          <template #default="scope">
            <el-tooltip content="查看详情" placement="top">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)"
                 class="action-btn"></el-button>
            </el-tooltip>
            <el-tooltip content="导入商品" placement="top">
              <el-button link type="primary" icon="upload" @click="handleImportProduct(scope.row)"
                class="action-btn"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                 class="action-btn"></el-button>
            </el-tooltip>
            <el-tooltip content="生成发票" placement="top">
              <el-button link type="" icon="Document" @click="handleInvoice(scope.row)"
                 class="action-btn"></el-button>
            </el-tooltip>
            <!-- <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['ymxbh:shipment:remove']" class="action-btn"></el-button>
            </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改订单管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body class="shipment-dialog">
      <el-form ref="shipmentFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="头程方式" prop="firstJourney">
          <el-input v-model="form.firstJourney" placeholder="请输入头程方式" />
        </el-form-item>
        <el-form-item label="发货时间" prop="shipmentsTime">
          <el-date-picker clearable v-model="form.shipmentsTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择发货时间" style="width: 100%">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm" class="btn-animate">确 定</el-button>
          <el-button @click="cancel" class="btn-animate">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改产品对话框 -->
    <el-dialog :title="productDialog.title" v-model="productDialog.visible" width="500px" append-to-body>
      <el-form ref="productFormRef" :model="productForm" :rules="productRules" label-width="80px">
        <!-- <el-form-item label="产品id" prop="id">
          <el-input v-model="form.id" placeholder="请输入产品id" />
        </el-form-item> -->
        <el-form-item label="产品图片" prop="image">
          <image-upload v-model="productForm.image" :return-url="true" />
        </el-form-item>
        <!-- <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="产品标条码" prop="fnsku">
          <el-input v-model="form.fnsku" placeholder="请输入产品标条码" />
        </el-form-item>
        <el-form-item label="产品名称英文" prop="msku">
          <el-input v-model="form.msku" placeholder="请输入产品名称英文" />
        </el-form-item> -->
        <el-form-item label="生产数量" prop="quantity">
          <el-input v-model="productForm.quantity" placeholder="请输入生产数量" />
        </el-form-item>
        <el-form-item label="每箱数量" prop="quantityinbox">
          <el-input v-model="productForm.quantityinbox" placeholder="请输入每箱数量" />
        </el-form-item>
        <el-form-item label="箱数" prop="boxNumber">
          <el-input v-model="productForm.boxNumber" placeholder="请输入箱数" />
        </el-form-item>
        <el-form-item label="对应箱号" prop="boxId">
          <el-input v-model="productForm.boxId" placeholder="请输入对应箱号" />
        </el-form-item>
        <el-form-item label="产品重量" prop="weight">
          <el-input v-model="productForm.weight" placeholder="请输入产品重量" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
            <el-input v-model="productForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <!-- <el-form-item label="货件追踪编号" prop="trackingNumber">
          <el-input v-model="form.trackingNumber" placeholder="请输入货件追踪编号" />
        </el-form-item>
        <el-form-item label="货件id" prop="shipmentId">
          <el-input v-model="form.shipmentId" placeholder="请输入货件id" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitFormProduct">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量导入订单对话框 -->
    <el-dialog :title="importDialog.title" v-if="importDialog.title === '订单数据导入'" v-model="importDialog.visible" width="500px" append-to-body>
      <el-form label-width="100px">
        <el-form-item label="Excel文件">
          <el-upload class="upload-demo" drag action="#" accept=".xlsx,.xls" :auto-upload="false"
            :on-change="handleFileChange" :show-file-list="true" :limit="1"
            :on-exceed="() => proxy.$modal.msgWarning('只能上传一个文件')">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否覆盖更新">
          <el-switch v-model="updateSupport" />
        </el-form-item>
      </el-form>
      <template #footer >
        <div class="dialog-footer">
          <!-- 下载模板按钮 -->
          <el-button type="primary" plain icon="Download" @click="downloadTemplateFile">下载模板</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="submitImport">确 定</el-button>
          <el-button @click="importDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量导入产品对话框 -->
    <el-dialog :title="importDialog.title" v-else v-model="importDialog.visible" width="500px" append-to-body>
      <el-form label-width="100px">
        <el-form-item label="Excel文件">
          <el-upload class="upload-demo" drag action="#" accept=".xlsx,.xls" :auto-upload="false"
            :on-change="handleFileChange" :show-file-list="true" :limit="1"
            :on-exceed="() => proxy.$modal.msgWarning('只能上传一个文件')">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否覆盖更新">
          <el-switch v-model="updateSupport" />
        </el-form-item>
      </el-form>
      <template #footer >
        <div class="dialog-footer">
          <!-- 下载模板按钮 -->
          <el-button type="primary" plain icon="Download" @click="downloadTemplateProductFile">下载模板</el-button>
          <el-button :loading="buttonLoading" type="primary" @click="submitImportProduct">确 定</el-button>
          <el-button @click="importDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

        <!-- 发票物流公司选择对话框 -->
    <el-dialog :title="invoiceDialog.title" v-model="invoiceDialog.visible" width="500px" append-to-body>
      <el-form label-width="120px">
        <el-form-item label="物流公司">
          <el-radio-group v-model="invoiceDialog.selectedLogistics">
            <el-radio 
              v-for="option in logisticsOptions" 
              :key="option.value" 
              :label="option.value"
            >
              {{ option.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="invoiceDialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="confirmGenerateInvoice">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Shipment" lang="ts">
import { listShipment, getShipment, delShipment, addShipment, updateShipment, batchImportOrder, batchImportProduct,mergeShipments,getFactoriesApi,syncOrderList,getEmployeesApi } from '@/api/ymxbh/shipment';
import { listProduct, getProduct, delProduct, addProduct, updateProduct }from '@/api/ymxbh/product'
import { ShipmentVO, ShipmentQuery, ShipmentForm } from '@/api/ymxbh/shipment/types';
import { ProductVO, ProductQuery, ProductForm } from '@/api/ymxbh/product/types';
import { factory } from 'typescript';
import { c } from 'node_modules/vite/dist/node/moduleRunnerTransport.d-DJ_mE5sf';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();

const shipmentList = ref<ShipmentVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const shipmentId = ref<string | number>('');

const factoryOptions = ref([]);
const employeeOptions = ref([]);

const importDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const fileToUpload = ref<File | null>(null);
const updateSupport = ref<boolean>(false); // 是否开启覆盖更新

const statusOptions = ref([
  { label: "待处理", value: "0" },
  { label: "待确认", value: "1" },
  { label: "审核中", value: "2" },
  { label: "已驳回", value: "3" },
  { label: "审核通过", value: "4" }
]);

const queryFormRef = ref<ElFormInstance>();
const shipmentFormRef = ref<ElFormInstance>();
const productFormRef = ref<ElFormInstance>();
const dateRangeOrderTime = ref<[string, string]>(['', '']);


const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const productDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ShipmentForm = {
  id: undefined,
  shipmentConfirmationId: undefined,
  warehouseId: undefined,
  factory: undefined,
  shopName: undefined,
  materialAndNumber: undefined,
  trackingNumber: undefined,
  employeeName: undefined,
  firstJourney: undefined,
  shippingAddress: undefined,
  orderTime: undefined,
  shipmentsTime: undefined,
  status: undefined,
  outerBoxLabel: undefined,
  // productLabel: undefined,
  mark: undefined,
  printDrawings: undefined,
  productList: []
}
const initProductData: ProductForm = {
  id: undefined,
  image: undefined,
  productName: undefined,
  fnsku: undefined,
  msku: undefined,
  quantity: undefined,
  quantityinbox: undefined,
  boxNumber: undefined,
  boxId: undefined,
  weight: undefined,
  remark: undefined,
  trackingNumber: undefined,
  shipmentId: undefined,
  productLabel: undefined
}
const data = reactive<PageData<ShipmentForm, ShipmentQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    shipmentConfirmationId: undefined,
    warehouseId: undefined,
    factory: undefined,
    shopName: undefined,
    materialAndNumber: undefined,
    trackingNumber: undefined,
    employeeName: undefined,
    firstJourney: undefined,
    shippingAddress: undefined,
    orderTime: undefined,
    shipmentsTime: undefined,
    status: undefined,
    type: 7,
    startTime: undefined,
    endTime: undefined,
    productName: undefined,
    fnsku: undefined,
    msku: undefined,
    params: {
    }
  },
  rules: {
  }
});
const productData = reactive<PageData<ProductForm, ProductQuery>>({
  form: {...initProductData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    image: undefined,
    productName: undefined,
    fnsku: undefined,
    msku: undefined,
    quantity: undefined,
    quantityinbox: undefined,
    boxNumber: undefined,
    boxId: undefined,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data);
const { queryParams: productQueryParams, form: productForm, rules: productRules } = toRefs(productData);

/**
 * 同步订单
 */
const handSyncOrderList = async () => { 
  try {
    loading.value = true;
    await syncOrderList();
    proxy?.$modal.msgSuccess("同步成功");
    getList(); // 同步成功后刷新数据列表
  } catch (error) {
    proxy?.$modal.msgError("同步失败");
  } finally {
    loading.value = false;
  }
};

/**
 * 合并订单
 */
const handleMerge = async () => {
  if (ids.value.length < 2) {
    proxy?.$modal.msgWarning("至少需要选择两个订单才能合并");
    return;
  }
  
  try {
    loading.value = true;
    await proxy?.$modal.confirm('确定要合并选中的 ' + ids.value.length + ' 个订单吗？');
    const response = await mergeShipments(ids.value);
    
    if (response.code === 200) {
      proxy?.$modal.msgSuccess("订单合并成功");
      await getList();
    } else {
      proxy?.$modal.msgError(response.msg || "订单合并失败");
    }
  } catch (error) {
    proxy?.$modal.msgError("订单合并失败");
  } finally {
    loading.value = false;
  }
};



// 获取工厂列表
const getFactories = async () => {
  try {
    const response = await getFactoriesApi();
    if (response.code === 200) {
      factoryOptions.value = response.data.map(item => ({
        id: item.roleId,
        name: item.roleName
      }));
    }
  } catch (error) {
    proxy?.$modal.msgError('获取工厂列表失败');
  }
};

// 获取员工列表
const getEmployees = async () => {
  try {
    const response = await getEmployeesApi();
    if (response.code === 200) {
      employeeOptions.value = response.data.map(item => ({
        id: item.userId,
        name: item.nickName
      }));
    }
  } catch (error) {
    proxy?.$modal.msgError('获取工厂账号列表失败');
  }
};

/** 查询订单管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listShipment(queryParams.value);
  shipmentList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  shipmentFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ShipmentVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 日期范围选择变化 */
const handleDateRangeChange = (val: [string, string] | null) => {
  if (val && val.length === 2) {
    queryParams.value.startTime = val[0];
    queryParams.value.endTime = val[1];
  } else {
    queryParams.value.startTime = undefined;
    queryParams.value.endTime = undefined;
  }
  handleQuery();
}

const downloadTemplateFile = () => {
  proxy?.download('/ymxbh/shipment/importTemplate', {
    ...queryParams.value
  }, `订单导入模板_${new Date().getTime()}.xlsx`)
}
const downloadTemplateProductFile = () => {
  proxy?.download('/ymxbh/product/importTemplate', {
    ...queryParams.value
  }, `产品导入模板_${new Date().getTime()}.xlsx`)
}

const handleFileChange = (file: any) => {
  if (file && file.raw) {
    fileToUpload.value = file.raw;
  } else {
    fileToUpload.value = file; // 兼容某些浏览器或组件行为差异
  }
}


const submitImport = async () => {
  if (!fileToUpload.value) {
    proxy?.$modal.msgWarning("请选择要上传的 Excel 文件");
    return;
  }

  buttonLoading.value = true;

  try {
    const res = await batchImportOrder(fileToUpload.value, updateSupport.value);

    if (res && res.code === 200) {
      proxy?.$modal.msgSuccess(res.msg);

    }else {
      // proxy?.$modal.msgError("导入失败，请检查文件内容");
      proxy?.$modal.msgError(res.msg);
    }
  } catch (error) {
    proxy?.$modal.msgError("导入异常");
  } finally {
    buttonLoading.value = false;
    importDialog.visible = false;
    getList(); // 刷新列表
  }
};

const submitImportProduct = async () => {
  if (!fileToUpload.value) {
    proxy?.$modal.msgWarning("请选择要上传的 Excel 文件");
    return;
  }

  buttonLoading.value = true;

  try {
    const res = await batchImportProduct(fileToUpload.value, updateSupport.value,shipmentId.value);

    if (res && res.code === 200) {
      proxy?.$modal.msgSuccess(res.msg);

    }else {
      // proxy?.$modal.msgError("导入失败，请检查文件内容");
      proxy?.$modal.msgError(res.msg);
    }
  } catch (error) {
    proxy?.$modal.msgError("导入异常");
  } finally {
    buttonLoading.value = false;
    importDialog.visible = false;
    getList(); // 刷新列表
  }
};

const handleImport = () => {
  fileToUpload.value = null;
  updateSupport.value = false;
  importDialog.visible = true;
  importDialog.title = "订单数据导入";
  reset();
};

const handleImportProduct = (row?: ShipmentVO) => {
  fileToUpload.value = null;
  updateSupport.value = false;
  importDialog.visible = true;
  importDialog.title = "产品数据导入";
  // 设置当前选中的货件ID
  if (row && row.id) {
    shipmentId.value = row.id;
  }
  reset();
};



/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加订单";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ShipmentVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getShipment(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改订单";
}

/** 修改按钮操作 */
const handleUpdateProduct = async (row?: ShipmentVO) => {
  reset();
  const _id = row?.id
  const res = await getProduct(_id);
  Object.assign(productForm.value, res.data);
  productDialog.visible = true;
  productDialog.title = "修改产品";
}



/** 查看详情 */
const handleView = (row: ShipmentVO) => {
  router.push({
    path: '/ymxbh/shipment/detail',
    query: { id: row.id }
  });
}

/** 提交按钮 */
const submitForm = () => {
  shipmentFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateShipment(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addShipment(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 提交按钮 */
const submitFormProduct = () => {
  productFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (productForm.value.id) {
        await updateProduct(productForm.value).finally(() =>  buttonLoading.value = false);
      } else {
        // await addShipment(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      productDialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: ShipmentVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除订单管理编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delShipment(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('ymxbh/shipment/export', {
    ...queryParams.value,
    ids: ids.value
  }, `shipment_${new Date().getTime()}.xlsx`)
}


/** 生成发票 */
// const handleInvoice = (row: ShipmentVO) => {
//   proxy?.download('ymxbh/shipment/generateInvoice', {
//     // ...queryParams.value,
//     id: row.id,
//     type: 
//   }, `invoice_${new Date().getTime()}.xlsx`)
// }

/** 生成发票对话框 */
const invoiceDialog = reactive({
  visible: false,
  title: '选择物流公司',
  selectedLogistics: 0
});

const logisticsOptions = [
  { label: '千安物流', value: 0 },
  { label: '森磊物流', value: 1 }
];

/** 生成发票 */
const handleInvoice = (row: ShipmentVO) => {
  // 保存当前行数据
  form.value = { ...row };
  // 重置选择
  invoiceDialog.selectedLogistics = 0;
  // 显示对话框
  invoiceDialog.visible = true;
}

/** 确认生成发票 */
const confirmGenerateInvoice = async () => {
  
  try {
    
    await proxy?.download('ymxbh/shipment/generateInvoice', {
      id: form.value.id,
      type: invoiceDialog.selectedLogistics
    }, `invoice_${new Date().getTime()}.xlsx`);

    invoiceDialog.visible = false;
    proxy?.$modal.msgSuccess("发票生成成功");
  } catch (error) {
    proxy?.$modal.msgError("发票生成失败");
  } finally {
    loading.value = false;
  }
}

onMounted(() => {
  getList();
  getFactories();
  getEmployees();
  // getAccounts();
});
</script>

<style lang="scss" scoped>
.search-card {
  :deep(.el-card__body) {
    padding: 20px;
  }
}

.table-card {
  :deep(.el-card__body) {
    padding: 15px;
  }
}

.shipment-table {
  width: 100%;
  font-size: 14px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  :deep(.shipment-table-header) {
    background: linear-gradient(180deg, #f5f7fa 0%, #ebedf0 100%) !important;
    color: #303133;
    font-weight: 600;
    th {
      background: transparent !important;
    }
  }
  
  :deep(.shipment-table-row) {
    transition: all 0.3s ease;
    
    &:hover {
      background-color: #f5f7fa !important;
      transform: translateY(-1px);
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    }
    
    &:nth-child(even) {
      background-color: #fafafa;
    }
  }
  
  :deep(.el-table__expanded-cell) {
    padding: 20px 30px !important;
    background-color: #fafbfc;
  }
}

.product-table-container {
  padding: 15px;
  background: linear-gradient(180deg, #ffffff 0%, #f9fafb 100%);
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.product-table {
  :deep(.product-table-header) {
    background: linear-gradient(180deg, #f0f2f5 0%, #e7e9ec 100%) !important;
    color: #606266;
    font-weight: 500;
    th {
      background: transparent !important;
    }
  }
}

.product-image {
  border-radius: 4px;
  transition: transform 0.3s ease;
  
  &:hover {
    transform: scale(1.1);
  }
}

.no-image {
  color: #909399;
  font-size: 12px;
}

.action-btn {
  margin: 0 3px;
  transition: all 0.3s;
  
  &:hover {
    transform: scale(1.2);
  }
}

.btn-animate {
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  }
}

.shipment-dialog {
  :deep(.el-dialog__header) {
    background: linear-gradient(120deg, #e0e6ed 0%, #d1d8e0 100%);
    padding: 15px 20px;
    border-top-left-radius: 8px;
    border-top-right-radius: 8px;
  }
  
  :deep(.el-dialog__body) {
    padding: 25px 30px;
  }
}

.dialog-footer {
  padding: 15px 20px;
  text-align: right;
  border-top: 1px solid #ebeef5;
  margin: 0 -20px -10px;
}

:deep(.el-table__cell) {
  padding: 10px 0;
}

:deep(.el-table .el-table__cell) {
  .cell {
    padding: 0 10px;
  }
}
// 小字体表格样式
:deep(.small-font) {
  font-size: 10px;
  
  .el-table__cell {
    font-size: 10px;
  }
  
  .cell {
    font-size: 10px;
  }
}

@media (max-width: 768px) {
  .shipment-table {
    font-size: 12px;
  }
  
  :deep(.el-table .el-table__cell) {
    .cell {
      padding: 0 5px;
    }
  }
}
</style>